import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Steps } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as datetime from '../../utils/datetime'
import dataEditCreate from '../addons/DataEdit'
import dataTableCreate from '../addons/DataTable'
import dataImportCreate from '../addons/DataImport'
import * as IndiService from '../../services/ClientDiviWorkFlow';
const daoName = "IndiDiviWorkFlow";
const ButtonGroup = Button.Group;
const Step = Steps.Step;
const columns = [
    { title: '客户名称', dataIndex: 'CUNM', key: 'CUNM', width: 120, sorter: true, dispaly: true, filter: true },
    { title: '证件号码', dataIndex: 'IDNO', key: 'IDNO', width: 200, sorter: true, dispaly: true, filter: true },
    { title: '状态', dataIndex: 'STATE', key: 'STATE', width: 100, sorter: true, dispaly: true, render: data => { if (data === 0) { return '待审批' } else if (data === 1) { return '审批中' } else { return '已审批' } } },
    { title: '认定日期', dataIndex: 'DSDT', key: 'DSDT', width: 120, sorter: true, dispaly: true, filter: true, render: data => datetime.format(data, "yyyy-MM-dd") },
    { title: '客户经理1', key: 'EMID1', width: 150, sorter: true, dispaly: true, filter: true, render: data => data.User1.Name + '(' + data.User1.No + ')' },
    { title: '占比1(%)', dataIndex: 'DSVL1', key: 'DSVL1', width: 120, sorter: true, dispaly: true, filter: true, render: data => data * 100 },
    { title: '客户经理2', key: 'EMID2', width: 150, sorter: true, dispaly: true, filter: true, render: data => data.EMID2 === null ? '' : data.User2.Name + '(' + data.User2.No + ')' },
    { title: '占比2(%)', dataIndex: 'DSVL2', key: 'DSVL2', width: 120, sorter: true, dispaly: true, filter: true, render: data => data === null ? '' : data * 100 },
    { title: '客户经理3', key: 'EMID3', width: 150, sorter: true, dispaly: true, filter: true, render: data => data.EMID3 === null ? '' : data.User3.Name + '(' + data.User3.No + ')' },
    { title: '占比3(%)', dataIndex: 'DSVL3', key: 'DSVL3', width: 120, sorter: true, dispaly: true, filter: true, render: data => data === null ? '' : data * 100 },
    { title: '客户经理4', key: 'EMID4', width: 150, sorter: true, dispaly: true, filter: true, render: data => data.EMID4 === null ? '' : data.User4.Name + '(' + data.User4.No + ')' },
    { title: '占比4(%)', dataIndex: 'DSVL4', key: 'DSVL4', width: 120, sorter: true, dispaly: true, filter: true, render: data => data === null ? '' : data * 100 },
    { title: '客户经理5', key: 'EMID5', width: 150, sorter: true, dispaly: true, filter: true, render: data => data.EMID5 === null ? '' : data.User5.Name + '(' + data.User5.No + ')' },
    { title: '占比5(%)', dataIndex: 'DSVL5', key: 'DSVL5', width: 120, sorter: true, dispaly: true, filter: true, render: data => data === null ? '' : data * 100 },
];
const controls = [
    { name: 'CUNM', required: true, type: 'text', label: '客户名称', grid: 12 / 24, layout: { labelSpan: 8, wrapperSpan: 13 }, placeholder: '请输入完整的客户名称...' },
    { name: 'IDNO', required: true, type: 'text', label: '证件号码', grid: 12 / 24, layout: { labelSpan: 8, wrapperSpan: 13 }, placeholder: '请输入完整的证件号码...' },
    {
        name: "EMID1", label: "客户经理1", type: "search", grid: 12 / 24, required: true,
        dataType: "number", fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        layout: { labelSpan: 8, wrapperSpan: 13 }
    },
    { name: "DSVL1", label: '占比1(%)', type: "number", grid: 12 / 24, dataType: "number", required: true, layout: { labelSpan: 8, wrapperSpan: 13 } },
    {
        name: "EMID2", label: "客户经理2", type: "search", grid: 12 / 24,
        dataType: "number", fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        layout: { labelSpan: 8, wrapperSpan: 13 }
    },
    { name: "DSVL2", label: '占比2(%)', type: "number", grid: 12 / 24, dataType: "number", layout: { labelSpan: 8, wrapperSpan: 13 } },
    {
        name: "EMID3", label: "客户经理3", type: "search", grid: 12 / 24,
        dataType: "number", fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        layout: { labelSpan: 8, wrapperSpan: 13 }
    },
    { name: "DSVL3", label: '占比3(%)', type: "number", grid: 12 / 24, dataType: "number", layout: { labelSpan: 8, wrapperSpan: 13 } },
    {
        name: "EMID4", label: "客户经理4", type: "search", grid: 12 / 24,
        dataType: "number", fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        layout: { labelSpan: 8, wrapperSpan: 13 }
    },
    { name: "DSVL4", label: '占比4(%)', type: "number", grid: 12 / 24, dataType: "number", layout: { labelSpan: 8, wrapperSpan: 13 } },
    {
        name: "EMID5", label: "客户经理5", type: "search", grid: 12 / 24,
        dataType: "number", fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID" },
        layout: { labelSpan: 8, wrapperSpan: 13 }
    },
    { name: "DSVL5", label: '占比5(%)', type: "number", grid: 12 / 24, dataType: "number", layout: { labelSpan: 8, wrapperSpan: 13 } },
    { name: "DSDT", label: "认定日期", type: "date", grid: 12 / 24, dataType: "date", required: true, layout: { labelSpan: 8, wrapperSpan: 13 } },
]
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class IndiWorkFlow extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            cunm: ''
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID" }
        });
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20 }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showModelHandler(isAdd) {
        let key = null
        if (!isAdd) {
            const len = this.props.selectedRowKeys.length;
            if (len === 0) {
                message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
                return;
            }
            key = this.props.selectedRowKeys[len - 1]
        }
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    deleteHandler() {
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要删除的行！');
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除选中的${len}行数据吗？`,
            okText: '删除',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/remove`,
                    payload: { daoName, keys },
                });
            }
        });
    }
    edidOkHandler() {
        const form = this.refs.userForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                const { keyName, record } = this.props;
                let msg = "数据添加成功！"
                if (record[keyName]) {
                    values[keyName] = record[keyName];
                    t = `${daoName}/patch`
                    msg = "数据修改成功！"
                }
                controls.map((c, i) => {
                    if (c.type === 'cascader-select') {
                        let vs = values[c.name];
                        if (vs.length > 0) {
                            values[c.name] = vs[vs.length - 1];
                        } else {
                            values[c.name] = null;
                        }
                    }
                    if (c.dataType === "number") {
                        values[c.name] = values[c.name] === undefined ? 0 : Number(values[c.name])
                    } else if (c.dataType === "date" || c.dataType === "datetime") {
                        values[c.name] = !values[c.name] ? null : new Date(values[c.name])
                    } else {
                        values[c.name] = values[c.name] === undefined ? null : values[c.name]
                    }
                    if (c.multiple || c.type === 'checkbox-group') {
                        values[c.name] = values[c.name].join(',');
                    }
                })
                let dsvlSum = values.DSVL1 + values.DSVL2 + values.DSVL3 + values.DSVL4 + values.DSVL5;
                if (dsvlSum !== 100) {
                    message.error('占比必须为100%');
                    return
                }
                if ((values.EMID2 !== 0 && values.DSVL2 === 0) || (values.EMID2 === 0 && values.DSVL2 !== 0)) {
                    message.error('保存失败！请正确输入客户经理2和占比2');
                    return
                } else if ((values.EMID3 !== 0 && values.DSVL3 === 0) || (values.EMID3 === 0 && values.DSVL3 !== 0)) {
                    message.error('保存失败！请正确输入客户经理3和占比3');
                    return
                } else if ((values.EMID4 !== 0 && values.DSVL4 === 0) || (values.EMID4 === 0 && values.DSVL4 !== 0)) {
                    message.error('保存失败！请正确输入客户经理4和占比4');
                    return
                } else if ((values.EMID5 !== 0 && values.DSVL5 === 0) || (values.EMID5 === 0 && values.DSVL5 !== 0)) {
                    message.error('保存失败！请正确输入客户经理5和占比5');
                    return
                }
                if (values.EMID2 === 0 && values.DSVL2 === 0 && ((values.EMID3 !== 0 && values.DSVL3 !== 0) || (values.EMID4 !== 0 && values.DSVL4 !== 0) || (values.EMID5 !== 0 && values.DSVL5 !== 0)) ||
                    values.EMID3 === 0 && values.DSVL3 === 0 && ((values.EMID4 !== 0 && values.DSVL4 !== 0) || (values.EMID5 !== 0 && values.DSVL5 !== 0)) ||
                    values.EMID4 === 0 && values.DSVL4 === 0 && values.EMID5 !== 0 && values.DSVL5 !== 0) {
                    message.error('保存失败！请按顺序正确输入客户经理和占比');
                    return
                }
                if (values.EMID1 === values.EMID2 || values.EMID1 === values.EMID3 || values.EMID1 === values.EMID4 ||
                    values.EMID1 === values.EMID5 || values.EMID2 === values.EMID3 || values.EMID2 === values.EMID4 ||
                    values.EMID2 === values.EMID5 || values.EMID3 === values.EMID4 || values.EMID3 === values.EMID5 ||
                    values.EMID4 === values.EMID5) {
                    message.error('保存失败！客户经理不能重复！');
                    return
                }
                let IDNO = values.IDNO;
                values.DSVL1 = values.DSVL1 / 100;
                values.DSVL2 = values.DSVL2 / 100;
                values.DSVL3 = values.DSVL3 / 100;
                values.DSVL4 = values.DSVL4 / 100;
                values.DSVL5 = values.DSVL5 / 100;
                values.EMID2 = values.EMID2 === 0 ? null : values.EMID2
                values.EMID3 = values.EMID3 === 0 ? null : values.EMID3
                values.EMID4 = values.EMID4 === 0 ? null : values.EMID4
                values.EMID5 = values.EMID5 === 0 ? null : values.EMID5
                values.DSVL2 = values.DSVL2 === 0 ? null : values.DSVL2
                values.DSVL3 = values.DSVL3 === 0 ? null : values.DSVL3
                values.DSVL4 = values.DSVL4 === 0 ? null : values.DSVL4
                values.DSVL5 = values.DSVL5 === 0 ? null : values.DSVL5
                IndiService.SaveIndiWorkFlow({ daoName, values }
                ).then(function (data) {
                    if (data === 'OK') {
                        message.success("数据保存成功!")
                    }
                }).catch(function (ex) {
                    message.error(ex.toString().substring(ex.toString().indexOf('错误信息：'), ex.toString().length))
                });
                this.state.dataChange = true;
            }
        });
    };
    addHandler() {
        const form = this.refs.userForm.getForm();
        form.resetFields();
        this.props.dispatch({
            type: `${daoName}/setRecord`,
            payload: { record: {} },
        });
    };
    hideEditHandler() {
        const form = this.refs.userForm.getForm();
        form.resetFields();
        if (this.state.dataChange) {
            this.props.dispatch({
                type: `${daoName}/reload`,
                payload: { daoName },
            });
            this.state.dataChange = false;
        }
        this.props.dispatch({
            type: `${daoName}/hideEdit`
        });
    };
    render() {
        let { showEdit, record } = this.props
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        <ButtonGroup style={{ zIndex: 0 }}>
                            <Button onClick={this.showModelHandler.bind(this, true)}>新增</Button>
                            <Button onClick={this.showModelHandler.bind(this, false)}>修改</Button>
                            <Button onClick={this.deleteHandler.bind(this)}>删除</Button>
                        </ButtonGroup>
                    </div>
                    <Modal title="申请认定" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
                        footer={[
                            <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
                            <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
                        ]}
                    >
                        <Steps size="small" current={1}>
                            <Step title="Finished" />
                            <Step title="In Progress" />
                            <Step title="Waiting" />
                        </Steps>
                        <EditFrom ref="userForm" daoName={daoName} controls={controls} record={record} />
                    </Modal>
                    <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls} canExport={false} />
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
    return {
        showEdit,
        selectedRowKeys,
        keyName,
        record
    }
}
IndiWorkFlow = connect(mapStateToProps)(IndiWorkFlow)
export default IndiWorkFlow;

let render = (props) => React.createElement(IndiWorkFlow, props);
let f = new Factory()
f.set("IndiWorkFlow", render)
